package com.ac.scum.log.web.model.wechat.pay.service;

import com.ac.common.core.exception.BaseException;
import com.ac.scum.log.web.model.wechat.pay.mapper.PayPackMapper;
import com.ac.scum.log.web.model.wechat.pay.mapper.PayPackSubMapper;
import com.ac.scum.log.web.model.wechat.pay.mapper.TradeMapper;
import com.ac.scum.log.web.utils.user.CurrentUserUtil;
import com.ac.scum.pay.PayPack;
import com.ac.scum.pay.Trade;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class PayPackService extends ServiceImpl<PayPackMapper, PayPack> {
    private final PayPackMapper payPackMapper;
    private final PayPackSubMapper payPackSubMapper;
    private final TradeMapper tradeMapper;

    public List<PayPack> selectList() throws BaseException {
        List<PayPack> payPacks = payPackMapper.selectList(Wrappers.<PayPack>lambdaQuery().orderByAsc(PayPack::getSortId));
        payPacks.forEach(payPack -> payPack.setPayPackSubs(payPackSubMapper.selectPayPackSubsByPayPackId(payPack.getId())));

        List<Long> list = payPacks.stream().filter(PayPack::getOnlyOneFlag).map(PayPack::getId).toList();
        if (!list.isEmpty()) {
            List<Trade> trades = tradeMapper.selectList(Wrappers.lambdaQuery(Trade.class).in(Trade::getPayPackId, list).eq(Trade::getServerId, CurrentUserUtil.getCurrentServerId()).eq(Trade::getTradeState, "SUCCESS"));
            if (!trades.isEmpty()) {
                Map<Long, Trade> tradeMap = trades.stream().collect(Collectors.toMap(Trade::getPayPackId, Function.identity(), (o, o2) -> o2));
                payPacks.removeIf(item -> tradeMap.containsKey(item.getId()));
            }
        }

        return payPacks;
    }
}
